<?php declare(strict_types=1);

namespace app\admin\service;

use app\admin\model\UserIdcardAudit;
use think\facade\Db;
use think\facade\Log;

class AuditService
{
    /**
     * 认证列表
     * @return void
     */
    public function getUserAuditList($pageSize, $startDate, $endDate, $keywords, $status, $type){
        switch ($type){
            case 1:
                $items = Db::name('user_idcard_audit')->alias('a')
                    ->leftJoin('user u', 'a.user_id = u.id')
                    ->field(['u.nickname','u.avatar','u.mobile','a.id','a.user_id','a.status','a.create_time','a.auth_time'])
                    ->where(function ($query) use ($startDate, $endDate, $keywords, $type, $status){
                        if($startDate){
                            $query->where('a.create_time', '>=', strtotime($startDate. ' 00:00:00'));
                        }
                        if($endDate){
                            $query->where('a.create_time', '<=', strtotime($endDate.' 23:59:59'));
                        }
                        if($keywords){
                            $query->where('a.real_name|a.card_number', 'like', $keywords. '%');
                        }
                        if (isset($status) && $status != '') {
                            $query->where('a.status', $status);
                        }
                    })
                    ->order('a.create_time desc')
                    ->paginate($pageSize)->each(function($item) use ($type){
                        $item['type'] = $type;
                        return $item;
                    });
                break;
        }
        return $items;
    }

    /**
     * 实名审核
     * @param $id
     * @return void
     */
    public function getUserIdCradAuditItem($id){
        $model = new UserIdcardAudit();
        $item = $model->alias('a')
            ->leftJoin('user u', 'a.user_id = u.id')
            ->field(['u.nickname','u.avatar','u.mobile','a.*'])
            ->where('a.id', $id)
            ->find();
        if (!empty($item)) {
            $item->type = 1;
            $item->auth_field = $item->real_name . '&' . $item->card_number;
            $item->auth_images = json_decode($item->idcard_hand, true);
        }
        return $item;
    }

    /**
     * 审核用户身份证
     * @param $data
     * @return void
     */
    public function authUserIdCardStatus($data){
        $model = new UserIdcardAudit();
        $item = $model->find($data['id']);
        if (empty($item)) {
            return json(['code'=>1, 'msg'=>'记录不存在']);
        }
//        $redis = RedisPackage::getInstance();
//        $userProfileKey = RedisKeyConst::getUserProfileKey($item->user_id);
        Db::startTrans();
        try {
            $item->save(['id'=>$data['id'], 'status'=>$data['status'], 'remarks'=>$data['remarks'], 'authed_at'=>date("Y-m-d H:i:s")]);
            Db::commit();
            // 更新Redis状态
//            $redis::hMSet($userProfileKey, ['user_idcard_audit'=>$data['status'], 'user_idcard_audit_remarks'=>$data['remarks']]);
            // 发送服务通知
//            $WechatService = new WechatService();
//            $WechatService->sendAuditMessage($item->user_id, config('app.wechat.TemplateId.AUDIT_RESULT_NOTICE'), $data);
            return json(['code'=>0, 'msg'=>'审核成功']);
        } catch (\Exception $e) {
            Log::error("authUserIdCardStatus failed:". $e->getMessage());
            Db::rollback();
            return json(['code'=>1, 'msg'=>'审核失败，'. $e->getMessage()]);
        }
    }

    /**
     * 编辑用户银行账号
     * @param $data
     * @return void
     */
    public function bank($data)
    {
        if (empty($data)) {
            return false;
        }
        $model = new UserIdcardAudit();
        try {
            $item = $model->where('user_id', $data['user_id'])->find();
            if ($item) {
                $data['id'] = $item->id;
                $item->save($data);
            } else {
                $model->save($data);
            }
            return true;
        } catch (Exception $e) {
            Log::error("update user bank failed: " .$e->getMessage());
            return false;
        }
    }

    /**
     * 获取用户银行信息
     * @param $userId
     * @return void
     */
    public function getBank($userId)
    {
        $model = new UserIdcardAudit();
        return $model->where('user_id', $userId)->field('bank_no,bank_name')->find();
    }
}